﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ZX.SYS.Bussiness.Message;
using ZX.SYS.Library;
using ZX.DBModule;
using ZX.BLL.Extend;
using ZX.EHR.Library;
using ZX.BLL;
using ZX.SYS.Bussiness;
namespace ZX.Web.Message
{
    public  class MessageManager
    {
        private  Guid MsgID { get; set; }
        public  string Title { get; set; }
        public  string MsgTemplate { get; set; }
        public  string MsgContent { get; set; }
        public  string MessageType { get; set; }
        public  DateTime ExpectTime { get; set; }
        public  Guid AddUser { get; set; }
        private  DateTime PushTime { get; set; }
        public  Guid QueryID { get; set; }
        public  string ViewName { get; set; }
        public IList<DatMessageReceiver> MessageReceiverList{get;set;}
        private string _MessageReceiver;

        public string ReceiverType { get; set; }
        public  string MessageReceiver {
            get { return _MessageReceiver; }
            set
            {
                _MessageReceiver = value;
                if (!string.IsNullOrEmpty(_MessageReceiver))
                {
                    string[] ids = _MessageReceiver.TrimEnd(',').Split(',');
                    IList<DatMessageReceiver> MReceiver = new List<DatMessageReceiver>();
                    foreach (string userId in ids)
                    {
                        DatMessageReceiver mr = DatMessageReceiver.New();
                        mr.MsItemID = Guid.NewGuid();
                        mr.MsgID = MsgID;
                        mr.ReceiverID = new Guid(userId);
                        mr.ReceiverType = ReceiverType;
                        MReceiver.Add(mr);
                    }
                    MessageReceiverList = MReceiver;
                }
            
            } 
        }

        public int Priority { get; set; }
        public bool IsEmphasis { get; set; }
        public string SysType { get; set; }
        public   MessageManager()
        {
            MsgID = Guid.NewGuid();
            PushTime = DateTime.Now;
        }

        /// <summary>
        /// 消息器（支持定时发送）
        /// </summary>
        /// <param name="xTitle">标题</param>
        /// <param name="xMsgContent">消息内容</param>
        /// <param name="xMessageType">消息类型（0:系统内部信息,1:Mail,2:手机短信息,3,QQ信息）</param>
        /// <param name="xExpectTime">预计发送日</param>
        /// <param name="xAddUser">发送人</param>
        /// <param name="xQueryID">关联编号</param>
        /// <param name="xViewName">关联表名或视图名</param>
        /// <param name="xReceiverType">发送者类型（U:用户，D:部门，C：公司）</param>
        /// <param name="xMessageReceiver">发送者集GUID[A6E24AD3-0028-4CA6-852B-787401AAB402，F8693AD3-2A3F-4AFB-95D8-96CE21F9886E]</param>
        /// <param name="xPriority">优先级（字典表中取MessagePriority类型：0普能 1急 2紧急 3特急）</param>
        /// <param name="xIsEmphasis">是否重要（0：不重要 1：重要）</param>
        /// <param name="xSysType">系统类型 （SYS,CRM,EHR,BPM,KM）</param>
        public  MessageManager(string xTitle, string xMsgContent, string xMessageType, DateTime xExpectTime,
            Guid xAddUser, Guid xQueryID, string xViewName, string xReceiverType,string xMessageReceiver,
            int xPriority,bool xIsEmphasis,string xSysType)
        {
            MsgID = Guid.NewGuid();
            Title = xTitle;
            MsgTemplate = "";
            MsgContent = xMessageType;
            MessageType = xMessageType;
            ExpectTime = xExpectTime;
            AddUser = xAddUser;
            PushTime = DateTime.Now;
            QueryID = xQueryID;
            ViewName = xViewName;
            ReceiverType = xReceiverType;
            MessageReceiver = xMessageReceiver;
            Priority=xPriority;
            IsEmphasis=xIsEmphasis;
            if (!string.IsNullOrEmpty(xSysType)) { SysType = "SYS"; }
            else { SysType = xSysType; }

        }

        /// <summary>
        /// 即时消息（支持关联务业表及优先级）
        /// </summary>
        /// <param name="xTitle">标题</param>
        /// <param name="xMsgContent">消息内容</param>
        /// <param name="xMessageType">消息类型（0:系统内部信息,1:Mail,2:手机短信息,3,QQ信息）</param>
        /// <param name="xAddUser">发送人</param>
        /// <param name="xQueryID">关联编号</param>
        /// <param name="xViewName">关联表名或视图名</param>
        /// <param name="xReceiverType">发送者类型（U:用户，D:部门，C：公司）</param>
        /// <param name="xMessageReceiver">发送者集GUID[A6E24AD3-0028-4CA6-852B-787401AAB402，F8693AD3-2A3F-4AFB-95D8-96CE21F9886E]</param>
        /// <param name="xPriority">优先级（字典表中取MessagePriority类型：0普能 1急 2紧急 3特急）</param>
        /// <param name="xIsEmphasis">是否重要（0：不重要 1：重要）</param>
        /// <param name="xSysType">系统类型 （SYS,CRM,EHR,BPM,KM）</param>
        public  MessageManager(string xTitle, string xMsgContent, string xMessageType,
            Guid xAddUser, Guid xQueryID, string xViewName, string xReceiverType, string xMessageReceiver,
            int xPriority, bool xIsEmphasis, string xSysType)
        {
            MsgID = Guid.NewGuid();
            Title = xTitle;
            MsgTemplate = "";
            MsgContent = xMessageType;
            MessageType = xMessageType;
            ExpectTime = DateTime.Now; ;
            AddUser = xAddUser;
            PushTime = DateTime.Now;
            QueryID = xQueryID;
            ViewName = xViewName;
            ReceiverType = xReceiverType;
            MessageReceiver = xMessageReceiver;
            Priority = xPriority;
            IsEmphasis = xIsEmphasis;
            if (!string.IsNullOrEmpty(xSysType)) { SysType = "SYS"; }
            else { SysType = xSysType; }
        }

        /// <summary>
        /// 即时消息（支持消息优先级）
        /// </summary>
        /// <param name="xTitle">标题</param>
        /// <param name="xMsgContent">消息内容</param>
        /// <param name="xMessageType">消息类型（0:系统内部信息,1:Mail,2:手机短信息,3,QQ信息）</param>
        /// <param name="xAddUser">发送人</param>
        /// <param name="xReceiverType">发送者类型（U:用户，D:部门，C：公司）</param>
        /// <param name="xMessageReceiver">发送者集GUID[A6E24AD3-0028-4CA6-852B-787401AAB402，F8693AD3-2A3F-4AFB-95D8-96CE21F9886E]</param>
        /// <param name="xPriority">优先级（字典表中取MessagePriority类型：0普能 1急 2紧急 3特急）</param>
        /// <param name="xIsEmphasis">是否重要（0：不重要 1：重要）</param>
        /// <param name="xSysType">系统类型 （SYS,CRM,EHR,BPM,KM）</param>
        public  MessageManager(string xTitle, string xMsgContent, string xMessageType,
            Guid xAddUser, string xReceiverType, string xMessageReceiver,
             int xPriority, bool xIsEmphasis, string xSysType)
        {

            MsgID = Guid.NewGuid();
            Title = xTitle;
            MsgTemplate = "";
            MsgContent = xMsgContent;
            MessageType = xMessageType;
            ExpectTime = DateTime.Now; ;
            AddUser = xAddUser;
            PushTime = DateTime.Now;
            QueryID = new Guid("00000000-0000-0000-0000-000000000000");
            ViewName = "";
            ReceiverType = xReceiverType;
            MessageReceiver = xMessageReceiver;
            Priority = xPriority;
            IsEmphasis = xIsEmphasis;
            if (!string.IsNullOrEmpty(xSysType)) { SysType = "SYS"; }
            else { SysType = xSysType; }
        }

        /// <summary>
        /// 定时消息（支持消息优先级）
        /// </summary>
        /// <param name="xTitle">标题</param>
        /// <param name="xMsgContent">消息内容</param>
        /// <param name="xMessageType">消息类型（0:系统内部信息,1:Mail,2:手机短信息,3,QQ信息）</param>
        /// <param name="xExpectTime">预计发送日</param>
        /// <param name="xAddUser">发送人</param>
        /// <param name="xReceiverType">发送者类型（U:用户，D:部门，C：公司）</param>
        /// <param name="xMessageReceiver">发送者集GUID[A6E24AD3-0028-4CA6-852B-787401AAB402，F8693AD3-2A3F-4AFB-95D8-96CE21F9886E]</param>
        /// <param name="xPriority">优先级（字典表中取MessagePriority类型：0普能 1急 2紧急 3特急）</param>
        /// <param name="xIsEmphasis">是否重要（0：不重要 1：重要）</param>
        /// <param name="xSysType">系统类型 （SYS,CRM,EHR,BPM,KM）</param>
        public MessageManager(string xTitle, string xMsgContent, string xMessageType, DateTime xExpectTime,
            Guid xAddUser, string xReceiverType, string xMessageReceiver,
             int xPriority, bool xIsEmphasis, string xSysType)
        {

            MsgID = Guid.NewGuid();
            Title = xTitle;
            MsgTemplate = "";
            MsgContent = xMsgContent;
            MessageType = xMessageType;
            ExpectTime = xExpectTime;
            AddUser = xAddUser;
            PushTime = DateTime.Now;
            QueryID = new Guid("00000000-0000-0000-0000-000000000000");
            ViewName = "";
            ReceiverType = xReceiverType;
            MessageReceiver = xMessageReceiver;
            Priority = xPriority;
            IsEmphasis = xIsEmphasis;
            if (!string.IsNullOrEmpty(xSysType)) { SysType = "SYS"; }
            else { SysType = xSysType; }
        }
        /// <summary>
        /// 即时默认系统消息
        /// </summary>
        /// <param name="xTitle">标题</param>
        /// <param name="xMsgContent">消息内容</param>
        /// <param name="xMessageType">消息类型（0:系统内部信息,1:Mail,2:手机短信息,3,QQ信息）</param>
        /// <param name="xAddUser">发送人</param>
        /// <param name="xReceiverType">发送者类型（U:用户，D:部门，C：公司）</param>
        /// <param name="xMessageReceiver">发送者集GUID[A6E24AD3-0028-4CA6-852B-787401AAB402，F8693AD3-2A3F-4AFB-95D8-96CE21F9886E]</param>
        public MessageManager(string xTitle, string xMsgContent, string xMessageType,
            Guid xAddUser, string xReceiverType, string xMessageReceiver)
        {

            MsgID = Guid.NewGuid();
            Title = xTitle;
            MsgTemplate = "";
            MsgContent = xMsgContent;
            MessageType = xMessageType;
            ExpectTime = DateTime.Now; ;
            AddUser = xAddUser;
            PushTime = DateTime.Now;
            QueryID = new Guid("00000000-0000-0000-0000-000000000000");
            ViewName = "";
            ReceiverType = xReceiverType;
            MessageReceiver = xMessageReceiver;
            Priority = 0;
            IsEmphasis = false;
            SysType = "SYS";
        }

        //public void Send() 
        //{
           
        //    BDatMessageQueue mQ = new BDatMessageQueue(); // TODO: 初始化为适当的值
        //    DatMessageQueue msg = DatMessageQueue.New(); // TODO: 初始化为适当的值
        //    msg.MsgID = MsgID;
        //    msg.Title = Title;
        //    msg.MsgTemplate = MsgTemplate;
        //    msg.MsgContent = MsgContent;
        //    msg.MessageType = MessageType;
        //    msg.ExpectTime = ExpectTime;
        //    msg.AddUser = AddUser;
        //    msg.PushTime = PushTime;
        //    msg.QueryID = QueryID;//关联信息来源的编号
        //    msg.ViewName = ViewName;
        //    msg.Priority = Priority;
        //    msg.IsEmphasis = IsEmphasis;
        //    msg.SysType = SysType;
        //    mQ.AddMessage(msg, MessageReceiverList);


        //    PushMessages(DateTime.Now);
        
        //}
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <returns></returns>
        public string Send()
        {
           
            BDatMessageQueue mQ = new BDatMessageQueue(); // TODO: 初始化为适当的值
            DatMessageQueue msg = DatMessageQueue.New(); // TODO: 初始化为适当的值
            msg.MsgID = MsgID;
            msg.Title = Title;
            msg.MsgTemplate = MsgTemplate;
            msg.MsgContent = MsgContent;
            msg.MessageType = MessageType;
            msg.ExpectTime = ExpectTime;
            msg.AddUser = AddUser;
            msg.PushTime = PushTime;
            msg.QueryID = QueryID;//关联信息来源的编号
            msg.ViewName = ViewName;
            msg.Priority = Priority;
            msg.IsEmphasis = IsEmphasis;
            msg.SysType = SysType;
            mQ.AddMessage(msg, MessageReceiverList);


            return PushMessages(ExpectTime);

        }
        /// <summary>
        /// 推送比指定时间早的预定信息
        /// </summary>
        /// <param name="CurrentTime">当前指时间</param>
        public string PushMessages(DateTime CurrentTime)
        {
            string msgConde = "0";
            try
            {
                if (CurrentTime != null && CurrentTime != default(DateTime))
                {
                    BDatMessageQueue MQ = new BDatMessageQueue();
                    IList<DatMessageQueue> list = MQ.GetCurrentPushMessages(CurrentTime);

                    if (list != null && list.Count > 0)
                    {
                        foreach (DatMessageQueue mq in list)
                        {
                            //消息体写入历史表
                            if (!new BV_HistoryMessagePool().HistoryMsgExists(mq.MsgID))
                            {
                                DatHistoryMessageQueue hMQ = new DatHistoryMessageQueue();
                                hMQ.MsgID = mq.MsgID;
                                hMQ.Title = mq.Title;
                                hMQ.MsgTemplate = mq.MsgTemplate;
                                hMQ.MsgContent = mq.MsgContent;
                                hMQ.MessageType = mq.MessageType;
                                hMQ.ExpectTime = mq.ExpectTime;
                                hMQ.AddUser = mq.AddUser;
                                hMQ.QueryID = mq.QueryID;
                                hMQ.PushState = mq.PushState;
                                hMQ.AddTime = mq.AddTime;
                                hMQ.PushTime = mq.PushTime;
                                hMQ.Priority = mq.Priority;
                                hMQ.IsEmphasis = mq.IsEmphasis;
                                hMQ.SysType = mq.SysType;

                                hMQ.BaseEntityState = WorkState.New;
                                hMQ.SaveEntity();
                            }

                            PushReceivers(mq.MsgID);
                            msgConde = "1";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                msgConde = ex.Message;
            }
            return msgConde;
        }





        /// <summary>
        /// 推送指定信息
        /// </summary>
        /// <param name="messageId"></param>
        public void PushReceivers(Guid messageId)
        {
            try
            {
                if (messageId != null)
                {
                    BDatMessageQueue MQ = new BDatMessageQueue();
                    DatMessageQueue datMQ = MQ.getMessageQueue(messageId);
                    IList<DatMessageReceiver> Receivers = new BDatMessageReceiver().GetReceivers(messageId);
                    if (Receivers != null && Receivers.Count > 0)
                    {
                        DatMessagePool mp = null;
                        DatHistoryMessagePool Hmp = DatHistoryMessagePool.New();
                        BMessageItem Bm = new BMessageItem();
                        IList<BDatMessageQueue.Criteria> list = null;
                        IList<BDatMessageQueue.CriteriaUserString> listUser = null;
                        foreach (DatMessageReceiver mr in Receivers)
                        {
                            string recType = mr.ReceiverType;
                            switch (recType)
                            {
                                case "U"://用户
                                    
                                    if (!Bm.MsgExists(mr.MsgID, mr.ReceiverID))
                                    {
                                        string isSend = "0";
                                        //if (datMQ.MessageType == "2") 
                                        //{
                                        //    isSend = SendMobileMessages(mr.MsgID, mr.ReceiverID);
                                        //}
                                        DatUser u = new BUser().GetDatUserByUserId(mr.ReceiverID);
                                        hrEmployee emp = new BEmployee().getHrEmployee(u.EmpID);

                                        switch (datMQ.MessageType)
                                        {
                                            case "1":

                                                if (emp != null)
                                                {
                                                    string Email = emp.Email;
                                                    if (!string.IsNullOrEmpty(Email))
                                                    {
                                                        MailThread m = new MailThread();
                                                        m.subject = datMQ.Title;
                                                        m.bodyContent = datMQ.MsgContent;
                                                        m.toAddress = Email;
                                                        m.messageId = datMQ.MsgID.ToString();
                                                        m.Send();
                                                    }
                                                }

                                                break;
                                            case "2":
                                                if (emp != null)
                                                {
                                                    string phone = emp.PhoneNo;
                                                    if (!string.IsNullOrEmpty(phone))
                                                    {
                                                        MQOut outMSMessages = new MQOut();
                                                        outMSMessages.sendmessage(phone, datMQ.MsgContent);
                                                    }
                                                }                
                                                break;
                                            default:
                                                break;
                                        }
                                        mp = DatMessagePool.New();
                                        mp.MPoolID = Guid.NewGuid();
                                        mp.MsgID = mr.MsgID;
                                        mp.ReceiverID = mr.ReceiverID;
                                        mp.SendState = isSend;
                                        mp.SendTime = DateTime.Now;
                                        mp.BaseEntityState = WorkState.New;
                                        mp.SaveEntity();

                                        //Hmp = DatHistoryMessagePool.New();
                                        //Hmp.MPoolID = mp.MPoolID;
                                        //Hmp.MsgID = mp.MsgID;
                                        //Hmp.ReceiverID = mp.ReceiverID;
                                        //Hmp.SendState = mp.SendState;
                                        //Hmp.SendTime = mp.SendTime;
                                        //Hmp.BaseEntityState = WorkState.New;
                                        //Hmp.SaveEntity();
                                    }
                                    break;
                                case "D"://部门
                                    switch (datMQ.MessageType)
	                                {
                                        case "1":
                                            listUser = MQ.GetOrgAndUserByEmail(mr.ReceiverID);
                                            if (listUser.Count > 0)
                                            {
                                                //发送邮件集信息
                                                BDatMessageQueue.CriteriaUserString itemUser = listUser[0];
                                                MailThread m = new MailThread();
                                                m.subject = datMQ.Title;
                                                m.bodyContent = datMQ.MsgContent;
                                                m.toAddress = itemUser.UserStrings;
                                                m.messageId = datMQ.MsgID.ToString();
                                                m.Send();
                                               
                                            }
                                            break;
                                        case "2":
                                            listUser=MQ.GetOrgAndUserByMobileNo(mr.ReceiverID);
                                            if (listUser.Count > 0)
                                            {
                                                //发送手机集信息
                                                BDatMessageQueue.CriteriaUserString itemUser = listUser[0];
                                                MQOut outMSMessages = new MQOut();
                                                outMSMessages.sendmessage(itemUser.UserStrings, datMQ.MsgContent);
                                            }
                                            break;
                                        default:
                                            break;
	                                }
                              
                                    list = MQ.GetOrgAndUser(mr.ReceiverID);
                                    if (list.Count > 0)
                                    {
                                        foreach (BDatMessageQueue.Criteria item in list)
                                        {
                                            if (!Bm.MsgExists(mr.MsgID, item.userid))
                                            {
                                                string isSend = "0";
                                                if (datMQ.MessageType == "2")
                                                {
                                                    isSend = SendMobileMessages(mr.MsgID, mr.ReceiverID);
                                                }
                                                mp = DatMessagePool.New();
                                                mp.MPoolID = Guid.NewGuid();
                                                mp.MsgID = mr.MsgID;
                                                mp.ReceiverID = item.userid;
                                                mp.SendState = isSend;
                                                mp.SendTime = DateTime.Now;
                                                mp.BaseEntityState = WorkState.New;
                                                mp.SaveEntity();

                                                //Hmp = DatHistoryMessagePool.New();
                                                //Hmp.MPoolID = mp.MPoolID;
                                                //Hmp.MsgID = mp.MsgID;
                                                //Hmp.ReceiverID = mp.ReceiverID;
                                                //Hmp.SendState = mp.SendState;
                                                //Hmp.SendTime = mp.SendTime;
                                                //Hmp.BaseEntityState = WorkState.New;
                                                //Hmp.SaveEntity();
                                            }
                                        }
                                    }
                                    break;
                                case "C"://公司
                                    switch (datMQ.MessageType)
                                    {
                                        case "1":
                                            listUser = MQ.GetOrgAndUserByEmail(mr.ReceiverID);
                                            if (listUser.Count > 0)
                                            {
                                                //发送邮件集信息
                                                BDatMessageQueue.CriteriaUserString itemUser = listUser[0];
                                                MailThread m = new MailThread();
                                                m.subject = datMQ.Title;
                                                m.bodyContent = datMQ.MsgContent;
                                                m.toAddress = itemUser.UserStrings;
                                                m.messageId = datMQ.MsgID.ToString();
                                                m.Send();

                                            }
                                            break;
                                        case "2":
                                            listUser = MQ.GetOrgAndUserByMobileNo(mr.ReceiverID);
                                            if (listUser.Count > 0)
                                            {
                                                //发送手机集信息
                                                BDatMessageQueue.CriteriaUserString itemUser = listUser[0];
                                                MQOut outMSMessages = new MQOut();
                                                outMSMessages.sendmessage(itemUser.UserStrings, datMQ.MsgContent);
                                            }
                                            break;
                                        default:
                                            break;
                                    }
                                    list = MQ.GetOrgAndUser(mr.ReceiverID);
                                    if (list.Count > 0)
                                    {
                                        foreach (BDatMessageQueue.Criteria item in list)
                                        {
                                            if (!Bm.MsgExists(mr.MsgID, item.userid))
                                            {
                                                string isSend = "0";
                                                if (datMQ.MessageType == "2")
                                                {
                                                    isSend = SendMobileMessages(mr.MsgID, mr.ReceiverID);
                                                }
                                                mp = DatMessagePool.New();
                                                mp.MPoolID = Guid.NewGuid();
                                                mp.MsgID = mr.MsgID;
                                                mp.ReceiverID = item.userid;
                                                mp.SendState = isSend;
                                                mp.SendTime = DateTime.Now;
                                                mp.BaseEntityState = WorkState.New;
                                                mp.SaveEntity();

                                                //Hmp = DatHistoryMessagePool.New();
                                                //Hmp.MPoolID = mp.MPoolID;
                                                //Hmp.MsgID = mp.MsgID;
                                                //Hmp.ReceiverID = mp.ReceiverID;
                                                //Hmp.SendState = mp.SendState;
                                                //Hmp.SendTime = mp.SendTime;
                                                //Hmp.BaseEntityState = WorkState.New;
                                                //Hmp.SaveEntity();
                                            }
                                        }
                                    }
                                    break;

                            }
                        }
                        MQ.setPushState(messageId);//更新状态
                    }

                    //**********************

                }

            }
            catch (Exception ex)
            {

                throw ex;
            }
        }


        /// <summary>
        /// 发送手机信息。
        /// </summary>
        /// <param name="MsgID"></param>
        /// <param name="ReceiverID"></param>
        /// <returns></returns>
        public string SendMobileMessages(Guid MsgID, Guid ReceiverID) 
        {
            string isSend = "1";
            DatMessageQueue MQ = new BDatMessageQueue().getMessageQueue(MsgID);
            DatUser u = new BUser().GetDatUserByUserId(ReceiverID);
            hrEmployee emp = new BEmployee().getHrEmployee(u.EmpID);
            if (emp != null)
            {
                string phone = emp.PhoneNo;
                if (!string.IsNullOrEmpty(phone))
                {
                    MQOut outMSMessages = new MQOut();
                    //0成功
                    isSend = outMSMessages.sendmessage(phone, MQ.MsgContent);
                    if (isSend != "0") { isSend = "1"; }
                }
            }
            return isSend;
        }
    }
}
